<template>
  <div class="bg-white">
    <ZgDialog
      :width="addConfig.width"
      :top="addConfig.top"
      :title="addConfig.title"
      v-model="showAdd"
      @ok="onAddOk">
      <slot name="add"></slot>
    </ZgDialog>
    <ZgDialog
      :width="updateConfig.width"
      :top="updateConfig.top"
      :title="updateConfig.title"
      v-model="showUpdate"
      @ok="onUpdateOk">
      <slot name="update" :jsonStr="JSON.stringify(obj)"></slot>
    </ZgDialog>
    <ZgDialog
      :width="batchConfig.width"
      :top="batchConfig.top"
      :title="batchConfig.title"
      v-model="showBatch"
      @ok="onBatchOk">
      <slot name="batch" :ids="ids"></slot>
    </ZgDialog>
    <ZgDrawer
      width="80%"
      v-model="showAttach">
      <ZgEmpty v-if="obj===null"></ZgEmpty>
      <ZgAttach v-else :tableName="tableName" :tableId="obj.id"></ZgAttach>
    </ZgDrawer>
    <ZgDrawer
      :width="sortConfig.width"
      :top="sortConfig.top"
      :title="sortConfig.title"
      v-model="showSort"
      @ok="onSortOk">
      <slot name="sort" :list="list"></slot>
      <div slot="extra">
        <a-button type="primary" @click="onSortOk">保存</a-button>
      </div>
    </ZgDrawer>
    <div class="pos-rlt" :style="{paddingLeft:`${fixedLeft?fixedLeftWidth:0}px`}">
      <div
        v-if="fixedLeft"
        class="pos-abs bg-white"
        :style="{
          boxSizing:`border-box`,
          width:`${fixedLeftWidth}px`,
          top:'0',
          left:'0',
          borderRight:'solid 1px #e6e6e6',
          height:`${winHeight-150}px`}">
        <div class="pd15">
          <div class="mt10 mb20">
            <span class="pd10 fs18">{{ currFilter.name }}</span>
            <span class="fs14 ml10 mr10">共{{ currFilter.count }}条</span>
          </div>
          <div class="fs14">
            <div class="pl10 mb10 info">选择视图</div>
            <div @click="onFilterClick(f)" :class="{curr:f.id===filterId}" class="flx-b filter" v-for="(f,i) in filterList" :key="`filter_v1_${i}`">
              <div>{{ f.name }}</div>
              <div>{{ f.count }}</div>
            </div>
          </div>
        </div>
        <div class="pos-abs wfull left-bottom flx-s fs14">
          <a-switch v-model="fixedLeft" size="small" class="mr5"></a-switch>
          固定视图在左侧
        </div>
      </div>
      <a-card :bordered="false" size="small">
        <div slot="title" class="flx-b">
          <div>
            {{ title }}
            <span v-if="!fixedLeft">
              <a-divider type="vertical"></a-divider>
              <a-popover
                v-model="showFilterList"
                placement="bottomLeft"
                trigger="click">
                <template slot="content">
                  <div
                    @click="onFilterClick(f)"
                    :class="{curr:f.id===filterId}"
                    class="flx-b filter"
                    v-for="(f,i) in filterList"
                    :key="`filter_v2_${i}`">
                    <div>{{ f.name }}</div>
                    <div>{{ f.count }}</div>
                  </div>
                  <div class="flx-a" style="border-top:solid 1px #e6e6e6;margin:15px -16px 0;padding:5px 10px 0;">
                    <a-switch v-model="fixedLeft" size="small" class="mr5"></a-switch>
                    <span>固定视图在左侧</span>
                  </div>
                </template>
                <template slot="title">
                  <div class="flx-b">
                    <div>选择过滤器</div>
                    <div class="cpt" @click="showFilterList=false">
                      <i class="fa fa-times"/>
                    </div>
                  </div>
                </template>
                <span @click="showFilterList=!showFilterList" class="cpt">
                  <span>{{ currFilter.name }}</span>
                  <span class="fs14 ml10 mr10">共{{ currFilter.count }}条</span>
                  <i class="fa" :class="`fa-caret-${showFilterList?'up':'down'}`"/>
                </span>
              </a-popover>
            </span>
          </div>
          <div class="flx-e">
            <a-input
              ref="searchInput"
              v-if="showSearch"
              v-model.trim="searchStr"
              class="w240 mr10"
              :placeholder="placeholder"
              @blur="onSearchInputBlur"
              @keyup.enter.native="onSearchInputEnter"
            >
              <a-icon slot="prefix" type="search" />
            </a-input>
            <a-tooltip v-else title="搜索" placement="top">
              <div class="btn flx-c" @click="showSearchInput">
                <i class="fa fa-search"/>
              </div>
            </a-tooltip>
            <a-tooltip title="刷新" placement="top">
              <div class="btn flx-c" @click="search">
                <i class="fa fa-refresh"/>
              </div>
            </a-tooltip>
            <a-tooltip title="筛选" placement="top">
              <div v-if="opt.showConditionBtn" class="btn flx-c" @click="toggleCondition">
                <i class="fa" :class="showCondition?'fa-compress':'fa-filter'"/>
              </div>
            </a-tooltip>
            <a-tooltip title="切换视图" placement="top">
              <div v-if="opt.showLayoutMode" class="btn flx-c" @click="toggleListMode">
                <i class="fa" :class="listMode?'fa-bars':'fa-th'"/>
              </div>
            </a-tooltip>
            <ZgDropdown
              v-if="opt.showBatchBtn"
              :opts="batchBtns"
              type="link"
              class="mr10"
              @click="toBatch">
              批量操作<i class="fa fa-angle-down ml3"/>
            </ZgDropdown>
            <span>
              <a-dropdown v-if="opt.showBatchAddBtn" class="ml10">
                <a-menu slot="overlay">
                  <a-menu-item v-for="(btn,i) in extraAddBtns" :key="`extra_btn_${i}`">
                    <span @click="onExtraAddBtnClick(i)">{{ btn }}</span>
                  </a-menu-item>
                </a-menu>
                <a-button type="primary">
                  {{ addBtnName }}<i class="fa fa-angle-down ml5"/>
                </a-button>
              </a-dropdown>
              <a-button
                class="ml10"
                v-if="opt.showAddBtn"
                type="primary"
                @click="toAdd"
              >
                <i :class="`fa fa-${addBtnIcon} mr5`" />{{ addBtnName }}
              </a-button>
            </span>
          </div>
        </div>
        <div
          v-show="showCondition"
          class="wfull mb15 pos-rlt"
          style="background:#f6f7f9;border-radius:4px;"
          :style="{height:`${opt.conditionHeight}px`}">
          <div class="pos-abs b15 r15 flx-e">
            <a-dropdown v-show="opt.manageFilter">
              <a-menu slot="overlay">
                <a-menu-item key="1" @click.native="saveFilter">存为新的数据视图</a-menu-item>
                <a-menu-item key="2" v-if="filterId!=='0'" @click.native="updateFilter">更新当前数据视图</a-menu-item>
                <a-menu-item key="3" v-if="filterId!=='0'" @click.native="delFilter">删除当前数据视图</a-menu-item>
              </a-menu>
              <a-button class="mr10">
                {{ currFilter.name }}<i class="fa fa-angle-down ml3"></i>
              </a-button>
            </a-dropdown>
            <ZgButton @click="resetCondition" type="default" class="mr10" icon="refresh">重置</ZgButton>
            <ZgButton @click="searchWithCondition" icon="search">查询</ZgButton>
          </div>
          <div class="pd15">
            <slot name="condition">
              <a-row>
                <a-col v-for="i in 12" :key="`condition${i}`" :span="6">
                  <div class="flx pd5">
                    <div class="w140">查询条件：</div>
                    <a-input></a-input>
                  </div>
                </a-col>
              </a-row>
            </slot>
          </div>
        </div>
        <div v-if="opt.showHeaderConfig && listMode" class="wfull pos-rlt">
          <div style="position:absolute;right:18px;top:10px;z-index:999;">
            <a-popover
              v-model="showHeaderConfig"
              placement="bottomRight"
              trigger="click">
              <template slot="content">
                <div class="fw8 pb10" style="border-bottom:solid 1px #e6e6e6">设置表头</div>
                <div class="scroll h360 pr10">
                  <slot name="headerConfig">
                  </slot>
                  <div class="h60"></div>
                </div>
                <div class="flx-e mt10 pt10" style="border-top:solid 1px #e6e6e6">
                  <ZgButton @click="loadDefaultHeaderConfig" type="link" icon="refresh" class="mr10">加载系统默认配置</ZgButton>
                  <ZgButton @click="saveHeaderConfig" icon="check">保存配置</ZgButton>
                </div>
              </template>
              <span @click="showHeaderConfig=!showHeaderConfig" class="cpt">
                <a-tooltip title="设置表头" placement="top">
                  <i class="fa fa-cog"/>
                </a-tooltip>
              </span>
            </a-popover>
          </div>
        </div>
        <slot name="tabs">
        </slot>
        <viewer class="viewer" :images="[]">
          <div :style="{height:`${winHeight+40-extraHeight-(showCondition?(opt.conditionHeight+15):0)}px`}">
            <slot name="thMode" v-if="!listMode" :list="dataList">
            </slot>
            <a-table
              v-else
              size="small"
              bordered
              :customHeaderRow="customHeaderRow"
              :pagination="false"
              :row-selection="opt.showBatchBtn?{ selectedRowKeys: ids, onChange: onSelectChange }:null"
              :data-source="list"
              :scroll="{ x: scrollX, y: winHeight-extraHeight-(showCondition?(opt.conditionHeight+15):0) }">

              <slot name="columns"></slot>
              <a-table-column v-if="opt.showBtn" fixed="right" :width="80" title="操作">
                <template slot-scope="text,record">
                  <a-dropdown>
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                      <i class="fa fa-ellipsis-h"/>
                    </a>
                    <a-menu slot="overlay">
                      <a-menu-item @click="toDel(record.id)" v-if="opt.showDelBtn"><i class="fa fa-trash mr5"/>删除</a-menu-item>
                      <a-menu-item @click="toUpdate(record)" v-if="opt.showUpdateBtn"><i class="fa fa-pencil mr5"/>修改</a-menu-item>
                      <a-menu-item @click="toAttach(record)" v-if="opt.showAttachBtn"><i class="fa fa-file mr5"/>附件</a-menu-item>
                      <a-menu-item v-show="btn.isShow(record)" v-for="btn in extraBtns" :key="`extra-btn-${btn.key}`" @click="onExtraBtnClick(btn.key,record)">
                        <i :class="`fa ${btn.icon} mr5`"/>{{ btn.name }}
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </template>
              </a-table-column>
            </a-table>
          </div>
        </viewer>
        <div class="flx-e mt10">
          <a-pagination
            showSizeChanger
            showQuickJumper
            v-model="page"
            :total="total"
            :pageSize="pageSize"
            :pageSizeOptions="pageSizeOptions"
            @change="onPageChange"
            @showSizeChange="onPageChange"
            :showTotal="total => `总共 ${total} 条记录`"
          />
        </div>
      </a-card>
    </div>
  </div>
</template>
<script>
import { pageMixin } from '@/core/page-mixin'
import ZgDialog from '@/comp/ZgDialog.vue'
import ZgDropdown from '@/comp/ZgDropdown.vue'
import ZgButton from '@/comp/ZgButton.vue'
export default {
  components: { ZgDialog, ZgDropdown, ZgButton },
  mixins: [pageMixin],
  props: {
    tableName: {
      type: String,
      default: 'default'
    },
    pageOpt: {
      type: Object,
      default: () => {
        return {}
      }
    },
    addOpt: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    updateOpt: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    batchOpt: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    sortOpt: {
      type: Object,
      default: () => {
        return {
        }
      }
    },
    batchBtns: {
      type: Array,
      default: () => {
        return [
          { label: '批量删除', code: 'del' },
          { label: '批量修改', code: 'update' },
          { label: '排序', code: 'sort' }
        ]
      }
    },
    extraAddBtns: {
      type: Array,
      default: () => {
        return ['单条数据', '导入数据', '初始化数据']
      }
    },
    extraBtns: {
      type: Array,
      default: () => {
        return [
          { key: 1, name: '上线', icon: 'fa-arrow-up', isShow: obj => { return obj.state === '下线' } },
          { key: 2, name: '下线', icon: 'fa-arrow-down', isShow: obj => { return obj.state === '运行' } }
        ]
      }
    },
    timeout: {
      type: Number,
      default: 5000
    },
    title: {
      type: String,
      default: '页面标题'
    },
    placeholder: {
      type: String,
      default: '输入关键字，按回车键进行搜索'
    },
    addBtnName: {
      type: String,
      default: '新增数据'
    },
    addBtnIcon: {
      type: String,
      default: 'plus'
    },
    extraHeight: {
      type: Number,
      default: 310
    },
    scrollX: {
      type: Number,
      default: 0
    },
    pageSizeOptions: {
      type: Array,
      default: () => {
        return ['10', '20', '30', '40', '50', '100']
      }
    }
  },
  computed: {
    opt () {
      return Object.assign({
        // 筛选功能
        showConditionBtn: false,
        // 批量功能
        showBatchBtn: true,
        // 单个添加功能
        showAddBtn: true,
        // 批量添加功能
        showBatchAddBtn: false,
        // 表头设置功能
        showHeaderConfig: false,
        // 布局模式设置功能
        showLayoutMode: false,
        // 显示数据操作按钮
        showBtn: true,
        // 显示数据删除按钮
        showDelBtn: true,
        // 显示数据更新按钮
        showUpdateBtn: true,
        // 显示数据附件按钮
        showAttachBtn: false,
        // 查询区域高度
        conditionHeight: 200,
        // 管理过滤器
        manageFilter: false
      }, this.pageOpt)
    },
    currFilter () {
      const arr = this.filterList.filter(t => {
        return t.id === this.filterId
      })
      return arr[0]
    },
    dataList () {
      return this.list
    },
    addConfig () {
      return Object.assign({
        width: '30%',
        top: '5%',
        title: '添加数据'
      }, this.addOpt)
    },
    updateConfig () {
      return Object.assign({
        width: '30%',
        top: '5%',
        title: '编辑数据'
      }, this.updateOpt)
    },
    batchConfig () {
      return Object.assign({
        width: '30%',
        top: '5%',
        title: '批量编辑数据'
      }, this.batchOpt)
    },
    sortConfig () {
      return Object.assign({
        width: '30%',
        top: '5%',
        title: '排序'
      }, this.sortOpt)
    }
  },
  data () {
    return {
      fixedLeft: false,
      fixedLeftWidth: 240,
      loading: false,
      showSearch: false,
      showAdd: false,
      showUpdate: false,
      showAttach: false,
      showBatch: false,
      showSort: false,
      showInfo: false,
      showCondition: false,
      showFilterList: false,
      showHeaderConfig: false,
      obj: null,
      filterId: '0',
      filterList: [
        { id: '0', name: '全部数据', count: 0, condition: '{}' }
      ]
    }
  },
  watch: {
    fixedLeft (v) {
      if (v) {
        this.showFilterList = false
      }
    },
    total (v) {
      this.$emit('total', v)
    }
  },
  mounted () {
    this.search()
  },
  methods: {
    customHeaderRow () {
      return {
        style: {
          background: '#f2f2f2'
        }
      }
    },
    onSelectChange (selectedRowKeys) {
      this.ids = selectedRowKeys
    },
    toggleListMode () {
      this.listMode = !this.listMode
    },
    onFilterClick (f) {
      this.filterId = f.id
      this.showFilterList = false
      this.$emit('filter', f, {
        searchStr: this.searchStr,
        page: this.page,
        pageSize: this.pageSize
      })
    },
    showSearchInput () {
      this.showSearch = true
      setTimeout(() => {
        this.$refs.searchInput.focus()
      })
    },
    onSearchInputBlur () {
      this.showSearch = false
      this.searchStr = ''
    },
    onSearchInputEnter () {
      this.search()
    },
    getPageParam () {
      return {
        searchStr: this.searchStr,
        page: this.page,
        pageSize: this.pageSize
      }
    },
    search () {
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, this.timeout)
      this.$emit('search', {
        searchStr: this.searchStr,
        page: this.page,
        pageSize: this.pageSize
      })
    },
    resetCondition () {
      this.$emit('resetCondition')
    },
    searchWithCondition () {
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, this.timeout)
      this.$emit('searchWithCondition', {
        searchStr: this.searchStr,
        page: this.page,
        pageSize: this.pageSize
      })
    },
    saveFilter () {
      this.$emit('saveFilter')
    },
    updateFilter () {
      this.$emit('updateFilter', this.currFilter)
    },
    delFilter () {
      this.$affirm('确定要删除这条视图数据么',
        () => {
          this.$http.post('/zg-autoform/filter/del', [this.filterId], () => {
            this.filterList = this.filterList.filter(t => {
              return t.id !== this.filterId
            })
            this.filterId = '0'
            this.$emit('filter', this.currFilter)
          })
        })
    },
    endSearch (opt) {
      this.total = opt.total
      this.list = opt.list
      this.loading = false
    },
    addFilter (arr) {
      this.filterList = [].concat([{ id: '0', name: '全部数据', count: 200, condition: '{}' }]).concat(arr)
    },
    toAdd () {
      this.showAdd = true
    },
    onAddOk () {
      this.$emit('add')
    },
    hideAdd () {
      this.showAdd = false
    },
    toUpdate (obj) {
      this.obj = obj
      this.showUpdate = true
    },
    toAttach (obj) {
      this.obj = obj
      this.showAttach = true
    },
    onUpdateOk () {
      this.$emit('update')
    },
    hideUpdate () {
      this.showUpdate = false
    },
    toBatch (opt) {
      if (opt.code === 'batchSort') {
        this.showSort = true
        return
      }
      this.checkIds(ids => {
        if (opt.code === 'del') {
          this.$emit('del', ids)
        } else if (opt.code === 'update') {
          this.showBatch = true
        }
      }, '确定要批量操作这些数据')
    },
    onBatchOk () {
      this.$emit('batch')
    },
    hideBatch () {
      this.showBatch = false
    },
    onSortOk () {
      this.$emit('sort')
    },
    hideSort () {
      this.showSort = false
    },
    toDel (id) {
      this.confirm(
        () => {
          this.$emit('del', [id])
        },
        '确定要删除这条数据么'
      )
    },
    onExtraBtnClick (key, obj) {
      this.$emit('extraBtn', { key: key, obj: obj })
    },
    toggleCondition () {
      this.showCondition = !this.showCondition
    },
    onExtraAddBtnClick (i) {
      this.$emit('extraAdd', i)
    },
    handleCurrentChange (val) {
      this.$emit('select', JSON.parse(JSON.stringify(val)))
    },
    saveHeaderConfig () {
      this.$emit('saveHeader')
    },
    loadDefaultHeaderConfig () {
      this.$emit('loadDefaultHeader')
    },
    onPageChange (page, pageSize) {
      this.page = page
      this.pageSize = pageSize
      this.search()
    }
  }
}
</script>
<style lang="scss">
  .ant-table > .ant-table-content .ant-table-header {
      background: #f2f2f2;
  }
</style>
<style lang="scss" scoped>
  .btn{
    width:32px;
    height:32px;
    color:#999;
    &:hover{
      cursor:pointer;
      color:#2979ff
    }
  }
  .filter{
    padding:4px 10px;
    border-radius:3px;
    margin-bottom:4px;
    &.curr{
      background:#409EFF;
      color:#fff;
    }
    &:hover{
      cursor:pointer;
      color:#fff;
      background:#409EFF;
    }
  }
  .left-bottom {
    padding: 10px;
    box-sizing: border-box;
    border-top: solid 1px #e6e6e6;
    bottom: 0;
    left: 0;
  }
</style>
